<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<script src="./rem.js"></script>
		<title>地图</title>
	</head>
	<style type="text/css">
		* {
			padding: 0;
			margin: 0;
		}

		html,
		body {
			width: 100%;
			height: 100%;
			overflow: hidden;
		}

		#map {
			position: relative;
			width: 100%;
			height: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.loadinggif {
			width: .5rem;
			height: .5rem;
		}

		.gm-style-mtc {
			display: none;
		}

		.gmnoprint {
			display: none !important;
		}

		.gmnoprint.gm-bundled-control.gm-bundled-control-on-bottom {
			display: none;
		}

		.gm-control-active.gm-fullscreen-control {
			display: none;
		}

		[class^="https://maps.google.com/maps"] {
			display: none !important;
		}

		.controls {
			margin-top: 10px;
			border: 1px solid transparent;
			border-radius: 2px 0 0 2px;
			box-sizing: border-box;
			-moz-box-sizing: border-box;
			height: 32px;
			outline: none;
			box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
		}

		#pac-input {
			width: 6.8rem;
			height: .8rem;
			box-sizing: border-box;
			position: fixed !important;
			top: 1rem !important;
			left: .32rem !important;
			padding: 0 .32rem;
			right: .32rem !important;
		}

		.pac-logo:after {
			display: none !important;
		}

		.btn {
			position: fixed;
			right: .4rem;
			bottom: .8rem;
			width: 1.2rem;
			height: 1.2rem;
			background-image: linear-gradient(45deg, rgba(0, 187, 44, .6), rgba(0, 187, 44, 1));
			font-size: .24rem;
			line-height: 1.2;
			color: #fff;
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
			transition: all ease .3s;
			box-shadow: 0px 3px 15px rgba(0, 0, 0, 0.2);
		}
	</style>

	<body>
		<!-- <input id="pac-input" class="controls" type="text" placeholder="Search Box"> -->
		<div id="map">
			<img class="loadinggif" src="./loading.gif">
		</div>
		<!-- <div id="btn" class="btn" style="text-align: center;" >确定<br>选择</div> -->
	</body>
	<script src="./jquery-3.2.1.min.js"></script>
	<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
	<!-- <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB-BX-KGMARGyn8FveEPZZkR_DEF0fy00M&libraries=places&callback=initMap"
	 async defer></script> -->

  <!-- <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?AIzaSyCdbjmG3M5keeuFLoeaVNRTf_zTS917648&libraries=places&callback=initMap&v=weekly&sensor=false"
   async></script> -->

   <script
     src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB4y-lo0JcaAbW0C1VGSdbIKiYzjxmKCCM&callback&callback=initMap&v=weekly"
     async></script>

	<script type="text/javascript" charset="utf-8">
		var lngtxt = "";
		var lattxt = "";
		var addresstxt = "";


		var isMaploading = false;
		var isUniAppJSBridgeReady = false;

		var map;
		var marker;
		var infowindow;
		var geocoder = {};
		var markersArray = [];
		var language = getParam('language') || 'zh-cn';
		var lp = {
			"确定<br/>选择":{
				"zh-cn":"确定<br/>选择",
				"en":"OK<br/>choose",
				"it":"OK<br/>Scegli"
			}
		}
		// document.getElementById('btn').innerHTML = lp['确定<br/>选择'][language];

		/**
		 * 获取指定的URL参数值
		 * URL:http://www.quwan.com/index?name=tyler
		 * 参数：paramName URL参数
		 * 调用方法:getParam("name")
		 * 返回值:tyler
		 */
		function getParam(paramName) {
			paramValue = "", isFound = !1;
			if (this.location.search.indexOf("?") == 0 && this.location.search.indexOf("=") > 1) {
				arrSource = unescape(this.location.search).substring(1, this.location.search.length).split("&"), i = 0;
				while (i < arrSource.length && !isFound) arrSource[i].indexOf("=") > 0 && arrSource[i].split("=")[0].toLowerCase() ==
					paramName.toLowerCase() && (paramValue = arrSource[i].split("=")[1], isFound = !0), i++
			}
			return paramValue == "" && (paramValue = null), paramValue;
		}

		let lngLat = getParam('lngLat') || '';
		let addressInfo = JSON.parse(getParam('addressInfo')) || {};


		document.addEventListener('UniAppJSBridgeReady', function() {
			uni.getEnv(function(res) {
				this.isUniAppJSBridgeReady = true;
				initMap(true);
				// uni.postMessage({
				// 	data: {
				// 		action: 'test',
				// 		latitude: 'latitude',
				// 		longitude: 'longitude'
				// 	}
				// });
			});
		});


		// document.getElementById('btn').addEventListener('click', function() {
		// 	if(!isMaploading || !isUniAppJSBridgeReady) return false;
		// 	console.log(1111111111)
		// 	uni.postMessage({
		// 		data: {
		// 			action: 'chooseaddress',
		// 			latitude: lattxt,
		// 			longitude: lngtxt,
		// 			addresstxt: addresstxt
		// 		}
		// 	});
		// })


		function initMap(mode) {

			if(!mode) isMaploading = true;
			if(!isMaploading || !isUniAppJSBridgeReady) return false;


			// 获取当前地理位置
			if (navigator.geolocation) {

				if(addressInfo.latitude){
					lattxt = addressInfo.latitude;
					lngtxt = addressInfo.longitude;
					initAutocomplete();
					console.log(JSON.stringify(addressInfo));
					return false
				}

        if (lngLat) {
          lattxt = lngLat.split(',')[1];
          lngtxt = lngLat.split(',')[0];
          initAutocomplete();
          return false
        }

				navigator.geolocation.getCurrentPosition(function(position) {
					var coords = position.coords;
					lattxt = coords.latitude;
					lngtxt = coords.longitude;
					initAutocomplete()
				}, function(err) {
					console.log('navigator.geolocation error')
					lattxt = 38.9001875;
					lngtxt = -77.03658209999999;
					initAutocomplete()
				}, {
					enableHighAccuracy: true, //是否要求高精度的地理位置信息
					timeout: 10000, //对地理位置信息的获取操作做超时限制，如果再该事件内未获取到地理位置信息，将返回错误
					maximumAge: 60 * 1000 //设置缓存有效时间，在该时间段内，获取的地理位置信息还是设置此时间段之前的那次获得的信息，超过这段时间缓存的位置信息会被废弃
				})
			} else {
				// alert(globalLanguage.ditu.no_tip);
				alert("你的浏览器不支持HTML5来获取地理位置信息。");
			}
		}


		function initAutocomplete() {
			var latlng = new google.maps.LatLng(lattxt, lngtxt);
			console.log(google.maps.MapTypeId)
			var myOptions = {
				zoom: 13,
				center: latlng,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			map = new google.maps.Map(document.getElementById('map'), myOptions);

			geocoder = new google.maps.Geocoder(); //实例化地址解析
      console.log('~~~~~~~~~')
      console.log(geocoder.geocode)
			placeMarker({lat:lattxt-0,lng:lngtxt - 0});

			//监听点击地图事件
			// google.maps.event.addListener(map, 'click', function(event) {
			// 	// console.log(JSON.stringify(event),'监听点击地图事件');
			// 	placeMarker(event.latLng);
			// });
			// Create the search box and link it to the UI element.
			// var input = document.getElementById('pac-input');
			// var searchBox = new google.maps.places.SearchBox(input);
			// map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

			// console.log(JSON.stringify(searchBox), 'searchBox类');
			// 将搜索框结果偏向当前地图的视口
			// map.addListener('bounds_changed', function() {
			// 	searchBox.setBounds(map.getBounds());
			// 	// console.log(JSON.stringify(map.getBounds()),'bounds_changed');
			// });

			var markers = [];
			// Listen for the event fired when the user selects a prediction and retrieve
			// 侦听用户选择预测并检索时激发的事件

			// more details for that place.
			// 更多关于那个地方的细节。
			// searchBox.addListener('places_changed', function() {
			// 	var places = searchBox.getPlaces();
   //       console.log(places)
			// 	if (places.length == 0) {
			// 		return;
			// 	}
			// 	if (places.length == 1) {
			// 		console.log(places)
			// 		clearOverlays(infowindow); //清除地图中的标记
			// 		marker = new google.maps.Marker({
			// 			position: places[0].geometry.location,
			// 			map: map
			// 		});
			// 		markersArray.push(marker);
			// 		attachSecretMessage(marker, places[0].geometry.location, places[0].formatted_address + places[0].name);
			// 		var bounds = new google.maps.LatLngBounds();

			// 		if (places[0].geometry.viewport) {
			// 			// Only geocodes have viewport.
			// 			bounds.union(places[0].geometry.viewport);
			// 		} else {
			// 			bounds.extend(places[0].geometry.location);
			// 		}
			// 		map.fitBounds(bounds);
			// 		// console.log(JSON.stringify(places[0].geometry.location))
			// 		lattxt = places[0].geometry.location.lat();
			// 		lngtxt = places[0].geometry.location.lng();
			// 		// console.log('lattxt',lattxt);
			// 		addresstxt = places[0].formatted_address + (places[0].formatted_address.name || '');
			// 		return;
			// 	}

			// 	return false;

			// 	// Clear out the old markers.
			// 	markers.forEach(function(marker) {
			// 		marker.setMap(null);
			// 	});
			// 	markers = [];

			// 	// For each place, get the icon, name and location.
			// 	var bounds = new google.maps.LatLngBounds();
			// 	places.forEach(function(place) {
			// 		if (!place.geometry) {
			// 			console.log("Returned place contains no geometry");
			// 			return;
			// 		}
			// 		var icon = {
			// 			url: place.icon,
			// 			size: new google.maps.Size(71, 71),
			// 			origin: new google.maps.Point(0, 0),
			// 			anchor: new google.maps.Point(17, 34),
			// 			scaledSize: new google.maps.Size(25, 25)
			// 		};
			// 		//console.log(place.geometry.location.lat());
			// 		mapClick(place.geometry.location.lng(), place.geometry.location.lat(), place.name);
			// 		// Create a marker for each place.
			// 		markers.push(new google.maps.Marker({
			// 			map: map,
			// 			// icon: icon,
			// 			title: place.name,
			// 			position: place.geometry.location
			// 		}));

			// 		if (place.geometry.viewport) {
			// 			// Only geocodes have viewport.
			// 			// 只有地理代码才有视区。
			// 			bounds.union(place.geometry.viewport);
			// 		} else {
			// 			bounds.extend(place.geometry.location);
			// 		}
			// 	});
			// 	map.fitBounds(bounds);
			// });


		}

		function placeMarker(location) {
			clearOverlays(infowindow); //清除地图中的标记
			marker = new google.maps.Marker({
				position: location,
				map: map
			});
			markersArray.push(marker);
      console.log('~~~~~~~~~~~~~~')
      console.log(location)
			//根据经纬度获取地址
			if (geocoder.geocode) {
				geocoder.geocode({
					'location': location
				}, function(results, status) {
					console.log('~~~~~~~~~~~~~~')
					console.log(results)
					if (status == google.maps.GeocoderStatus.OK) {
						if (results[0]) {
							attachSecretMessage(marker, results[0].geometry.location, results[0].formatted_address);
						}
					} else {
						alert("Geocoder failed due to: " + status);
					}
				});
			}
		}

		//在地图上显示经纬度地址
		function attachSecretMessage(marker, piont, address) {
			lattxt = piont.lat()
			lngtxt = piont.lng()
			// addresstxt = address
			// var message = "<b>坐标:</b>" + piont.lat() + " , " + piont.lng() + "<br />" + "<b>地址:</b>" + address;
			var message = address;
			var infowindow = new google.maps.InfoWindow({
				content: message,
				size: new google.maps.Size(50, 50)
			});
			infowindow.open(map, marker);
			if (typeof(mapClick) == "function") mapClick(piont.lng(), piont.lat(), address);
		}

		//删除所有标记阵列中消除对它们的引用
		function clearOverlays(infowindow) {
			if (markersArray && markersArray.length > 0) {
				for (var i = 0; i < markersArray.length; i++) {
					markersArray[i].setMap(null);
				}
				markersArray.length = 0;
			}
			if (infowindow) {
				infowindow.close();
			}
		}

		function setiInit() {
			// 页面加载显示默认lng lat address---begin
			if (lattxt != '' && lngtxt != '' && addresstxt != '') {
				var latlng = new google.maps.LatLng(lattxt, lngtxt);
				marker = new google.maps.Marker({
					position: latlng,
					map: map
				});
				markersArray.push(marker);
				attachSecretMessage(marker, latlng, addresstxt);
			}
		}

		function mapClick(lng, lat, address) {
			// window.parent.document.getElementById("address_lng").value = lng;
			// window.parent.document.getElementById("address_lat").value = lat;
			// window.parent.document.getElementById("address").value = address;
		}
		window.onload = function() {
			setiInit();
		}
	</script>

</html>
